import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import 'package:labcloud_app/api/graphql/product_gql.dart';
import 'package:labcloud_app/api/graphql/user_gql.dart';
import 'package:labcloud_app/data/product.dart';
import 'package:labcloud_app/widget/async_image.dart';
import 'package:provider/provider.dart';
import 'package:labcloud_app/model/product/product_ad_model.dart';
import 'package:labcloud_app/model/user/user_cart_model.dart';
import 'package:labcloud_app/model/user/user_model.dart';

class ProductDetail extends StatefulWidget {
  const ProductDetail({super.key});

  @override
  State<ProductDetail> createState() => _ProductDetailState();
}

class _ProductDetailState extends State<ProductDetail> {
  String? productId;
  Product? product;
  bool isFavorite = false;
  bool _isLoading = true;
  int _quantity = 1; // 添加商品数量变量

  @override
  void initState() {
    super.initState();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    
    // 只在第一次加载时获取参数
    if (_isLoading && productId == null) {
      var args = ModalRoute.of(context)?.settings.arguments;
      if (args is Map) {
        productId = args['productId']?.toString();
        print('获取到的productId: $productId');
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  void _contactCustomerService() {
    // 联系客服逻辑
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('联系客服功能待实现')),
    );
  }

  void _toggleFavorite() {
    // 收藏/取消收藏逻辑
    setState(() {
      isFavorite = !isFavorite;
    });
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(isFavorite ? '已收藏' : '已取消收藏')),
    );
  }

  void _addToCart() async {
    // 使用UserCartModel的addToCart方法处理添加到购物车逻辑
    if (product != null) {
      final userCartModel = Provider.of<UserCartModel>(context, listen: false);
      final userModel = Provider.of<UserModel>(context, listen: false);

      
      if (productId != null && userModel.isLoggedIn) {
        try {
          final client = GraphQLProvider.of(context).value;
          final result = await userCartModel.addToCart(client, productId!, _quantity);
          
          if (result != null) {
            if (mounted) {
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(content: Text('已添加$_quantity件到购物车')),
              );
              
              // 可选：跳转到购物车页面
              // Navigator.pushNamed(context, '/shopping_cart');
            }
          } else {
            if (mounted) {
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('添加到购物车失败')),
              );
            }
          }
        } catch (error) {
          if (mounted) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(content: Text('添加到购物车失败: $error')),
            );
          }
        }
      } else if (!userModel.isLoggedIn) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('请先登录')),
          );
          // 可选：跳转到登录页面
          // Navigator.pushNamed(context, '/login');
        }
      } else {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('商品信息不完整')),
          );
        }
      }
    } else {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('商品信息不完整')),
        );
      }
    }
  }

  void _buyNow() {
    // 立即购买逻辑 - 跳转到订单提交页
    if (product != null) {
      Navigator.pushNamed(
        context,
        '/order_submit',
        arguments: {
          'product': product,
          'quantity': _quantity, // 传递选中的数量
        },
      );
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('商品信息不完整')),
      );
    }
  }

  // 增加商品数量
  void _increaseQuantity() {
    setState(() {
      _quantity++;
    });
  }

  // 减少商品数量
  void _decreaseQuantity() {
    if (_quantity > 1) {
      setState(() {
        _quantity--;
      });
    }
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(product?.title ?? '商品详情页'),
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : productId == null
              ? const Center(child: Text('无法加载商品详情'))
              : Query(
                  options: QueryOptions(
                    document: gql(ProductGQL.fetchProductDetail),
                    variables: {
                      'id': productId!,
                    },
                  ),
                  builder: (QueryResult result, {refetch, fetchMore}) {
                    if (result.isLoading) {
                      return const Center(child: CircularProgressIndicator());
                    }

                    if (result.hasException) {
                      return Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text('加载失败: ${result.exception.toString()}'),
                            const SizedBox(height: 16),
                            ElevatedButton(
                              onPressed: refetch,
                              child: const Text('重试'),
                            ),
                          ],
                        ),
                      );
                    }

                    if (result.data == null || 
                        result.data!['product'] == null || 
                        result.data!['product']['productById'] == null) {
                      return const Center(child: Text('暂无商品数据'));
                    }

                    // 解析GraphQL响应数据
                    final productData = result.data!['product']['productById'];
                    product = Product.fromJson(productData);

                    return SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 产品图片
                      SizedBox(
                        width: double.infinity,
                        height: 300,
                        child: product!.coverAddr != null
                            ? AsyncImageWidget(
                                imageUrl: product!.coverAddr!,
                                fit: BoxFit.cover,
                                width: double.infinity,
                                height: 300,
                              )
                            : Container(
                                color: Colors.grey[300],
                                child: const Icon(Icons.error),
                              ),
                      ),

                      // 产品基本信息
                      Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              product!.title ?? '未知产品',
                              style: const TextStyle(
                                fontSize: 20,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            const SizedBox(height: 8),
                            Row(
                              children: [
                                Text(
                                  '¥${product!.price ?? 0}',
                                  style: const TextStyle(
                                    fontSize: 24,
                                    color: Colors.red,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                                const Spacer(),
                                Row(
                                  children: [
                                    const Icon(Icons.star, color: Colors.orange, size: 20),
                                    Text(
                                      '${product!.rate ?? 0}',
                                      style: const TextStyle(fontSize: 16),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                            const SizedBox(height: 16),
                            Text('库存: ${product!.stockpile ?? 0}件'),
                            
                            // 添加数量选择器
                            const SizedBox(height: 16),
                            Row(
                              children: [
                                const Text(
                                  '数量: ',
                                  style: TextStyle(
                                    fontSize: 16,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                                const SizedBox(width: 10),
                                Container(
                                  decoration: BoxDecoration(
                                    border: Border.all(color: Colors.grey),
                                    borderRadius: BorderRadius.circular(4),
                                  ),
                                  child: Row(
                                    mainAxisSize: MainAxisSize.min,
                                    children: [
                                      IconButton(
                                        icon: const Icon(Icons.remove, size: 18),
                                        onPressed: _decreaseQuantity,
                                        padding: const EdgeInsets.all(0),
                                        constraints: const BoxConstraints(),
                                      ),
                                      Container(
                                        width: 40,
                                        height: 30,
                                        alignment: Alignment.center,
                                        child: Text(
                                          '$_quantity',
                                          style: const TextStyle(
                                            fontSize: 16,
                                            fontWeight: FontWeight.bold,
                                          ),
                                        ),
                                      ),
                                      IconButton(
                                        icon: const Icon(Icons.add, size: 18),
                                        onPressed: _increaseQuantity,
                                        padding: const EdgeInsets.all(0),
                                        constraints: const BoxConstraints(),
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                      
                      // 产品规格
                      if (product!.specificationList != null && product!.specificationList!.isNotEmpty)
                        Padding(
                          padding: const EdgeInsets.all(16.0),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              const Text(
                                '产品规格',
                                style: TextStyle(
                                  fontSize: 18,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              const SizedBox(height: 8),
                              Container(
                                decoration: BoxDecoration(
                                  border: Border.all(color: Colors.grey.shade300),
                                  borderRadius: BorderRadius.circular(8.0),
                                ),
                                child: Column(
                                  children: [
                                    ...product!.specificationList!.asMap().entries.map((entry) {
                                      final index = entry.key;
                                      final spec = entry.value;
                                      return Column(
                                        children: [
                                          Padding(
                                            padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 8.0),
                                            child: Row(
                                              children: [
                                                Expanded(
                                                  flex: 1,
                                                  child: Text(
                                                    spec.item ?? '',
                                                    style: const TextStyle(
                                                      fontWeight: FontWeight.w500,
                                                      color: Colors.grey,
                                                    ),
                                                  ),
                                                ),
                                                Expanded(
                                                  flex: 2,
                                                  child: Text(
                                                    spec.value ?? '',
                                                    style: const TextStyle(
                                                      color: Colors.black87,
                                                    ),
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),
                                          if (index < product!.specificationList!.length - 1)
                                            const Divider(height: 1, thickness: 1),
                                        ],
                                      );
                                    }).toList(),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),

                      // 分隔线
                      const Divider(),

                      // 产品详情
                      Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            const Text(
                              '产品详情',
                              style: TextStyle(
                                fontSize: 18,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            const SizedBox(height: 8),
                            Html(
                              data: product!.description ?? '<p>暂无详情</p>',
                              style: {
                                "body": Style(
                                  fontSize: FontSize(16.0),
                                ),
                                "p": Style(
                                  margin: Margins.only(bottom: 10.0),
                                ),
                              },
                            ),
                          ],
                        ),
                      ),

                      // 分隔线
                      const Divider(),

                      // 详细图片
                      if (product!.detailAddr != null)
                        Padding(
                          padding: const EdgeInsets.all(16.0),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              const Text(
                                '详细信息',
                                style: TextStyle(
                                  fontSize: 18,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              const SizedBox(height: 8),
                              SizedBox(
                                width: double.infinity,
                                child: product!.detailAddr != null
                                    ? AsyncImageWidget(
                                        imageUrl: product!.detailAddr!,
                                        fit: BoxFit.cover,
                                        width: double.infinity,
                                      )
                                    : Container(
                                        color: Colors.grey[300],
                                        child: const Icon(Icons.error),
                                      ),
                              ),
                            ],
                          ),
                        ),
                    ],
                  ),
                );
              },
            ),
      bottomNavigationBar: _isLoading || productId == null
          ? null
          : Container(
              height: 70,
              padding: const EdgeInsets.symmetric(horizontal: 16.0),
              decoration: const BoxDecoration(
                border: Border(top: BorderSide(color: Colors.grey)),
                color: Colors.white,
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  // 联系客服按钮
                  Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      IconButton(
                        icon: const Icon(Icons.chat_bubble_outline, size: 24),
                        onPressed: _contactCustomerService,
                      ),
                    ],
                  ),
                  
                  // 收藏按钮
                  Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      IconButton(
                        icon: Icon(
                          isFavorite ? Icons.favorite : Icons.favorite_border,
                          color: isFavorite ? Colors.red : null,
                          size: 24,
                        ),
                        onPressed: _toggleFavorite,
                      ),
                    ],
                  ),
                  
                  // 加入购物车按钮
                  Expanded(
                    child: Container(
                      height: 40,
                      margin: const EdgeInsets.only(left: 8, right: 4),
                      child: ElevatedButton(
                        onPressed: _addToCart,
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.orange,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(20),
                          ),
                        ),
                        child: const Text(
                          '加入购物车',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 14,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ),
                  ),
                  
                  // 立即购买按钮
                  Expanded(
                    child: Container(
                      height: 40,
                      margin: const EdgeInsets.only(left: 4, right: 8),
                      child: ElevatedButton(
                        onPressed: _buyNow,
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.red,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(20),
                          ),
                        ),
                        child: const Text(
                          '立即购买',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 14,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
    );
  }
}